<template>
  <div class="Summary">
    <el-row :gutter="20">
      <el-col :span="10">
        <summary-display :collectData="collect"></summary-display>
        <echart-pie :chartData="chartData"></echart-pie>
        <div class="feature">
          <div class="AutoNum">
            <span>开启</span>
            <el-input-number
              v-model="AutoNum"
              :min="0"
              @change="handleChange"
            />
            <span>分钟后刷新数据</span>
            还剩<span class="countdown">{{ timerValue }}</span
            >秒
          </div>
          <el-button type="primary" @click="collectDataExport" v-if="isAdmin==='admin'" >导出私信数据</el-button>
        </div>
      </el-col>
      <el-col :span="14">
        <details-table :tableData="tableData"></details-table>
      </el-col>
    </el-row>
  </div>
  <div class="line">
    <echart-line :chartData="chartDataLine"></echart-line>
  </div>
</template>

<script setup>
import SummaryDisplay from "../components/SummaryDisplay.vue";
import EchartPie from "../components/echart/EchartPie.vue";
import DetailsTable from "../components/DetailsTable.vue";
import EchartLine from "../components/echart/EchartLine.vue";
import { ref, onMounted, onBeforeUnmount } from "vue";
import {
  collectAPI,
  collectPieAPI,
  collectLineAPI,
  collectTableAPI,
  collectDataExportAPI,
} from "../api/DataAnalyticsDashboard";
import { ElMessage } from 'element-plus'
const chartData = ref([]);
const collectPieData = async () => {
  const response = await collectPieAPI();
  if (response.status == 200) {
    chartData.value = response.data;
  }
};
const chartDataLine = ref();
const collectDataLine = async () => {
  const response = await collectLineAPI();
  if (response.status == 200) {
    chartDataLine.value = response.data;
  }
};

const collect = ref({});
const collectData = async () => {
  const response = await collectAPI();
  if (response.status == 200) {
    collect.value = response.data;
  }
};
const tableData = ref([]);

const collectDataTable = async () => {
  const response = await collectTableAPI();
  if (response.status === 200) {
    const cachedData = JSON.parse(localStorage.getItem("cachedData")) || [];
    tableData.value = response.data.map((item, index) => {
      // 找到与 item.name 匹配的 cachedData
      const cachedItem =
        cachedData.find(({ name }) => name === item.name) || {};
      const previousPersonalLetter = cachedItem.personalLetter || 0; // 获取对应的 personalLetter

      // 如果 previousPersonalLetter 为 0，personalLetterDifference 也设置为 0
      const personalLetterDifference =
        previousPersonalLetter === 0
          ? 0
          : Number(item.personalLetter) === Number(previousPersonalLetter)
          ? 0
          : item.personalLetter - previousPersonalLetter;

      return {
        ...item,
        id: index, // 使用 map 的索引作为 id
        Increase: personalLetterDifference,
      };
    });
    // 更新缓存
    const newCache = response.data.map(({ name, personalLetter }) => ({
      name,
      personalLetter,
    }));
    localStorage.setItem("cachedData", JSON.stringify(newCache));
  }
};
const AutoNum = ref(0);
const timerValue = ref(0);
let intervalId = null;

const handleChange = (value) => {
  // 清除之前的定时器
  if (intervalId) {
    clearInterval(intervalId);
  }

  if (value > 0) {
    // 设置新的定时器
    timerValue.value = value * 60; // 设置倒计时时间（秒）

    intervalId = setInterval(async() => {
      if (timerValue.value > 0) {
        timerValue.value -= 1; // 每秒减1
      } else {
        clearInterval(intervalId);
        await refreshData();
      }
    }, 1000);
  }
};

const refreshData = async () => {
  try {
    await collectData();
    await collectPieData();
    await collectDataLine();
    await collectDataTable();
  } catch (error) {
    console.error("Error refreshing data:", error);
  }
  timerValue.value = AutoNum.value * 60;
  handleChange(AutoNum.value);
};

const collectDataExport = async () => {
  try {
    const response = await collectDataExportAPI();
    // 如果 response 是一个 Blob，继续处理
    if (response instanceof Blob) {
      const url = URL.createObjectURL(response);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '导出私信数据.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    } else {
      ElMessage({
        message: '文件导出失败，请重试',
        type: 'error',
      });
    }
  } catch (error) {
    console.error('下载文件时发生错误:', error);
    ElMessage({
      message: '下载文件时发生错误',
      type: 'error',
    });
  }
};
const userData=JSON.parse(localStorage.getItem('userData'))
const isAdmin=ref(userData.role)

onBeforeUnmount(() => {
  localStorage.removeItem("cachedData");
  if (intervalId) {
    clearInterval(intervalId);
  }
});

onMounted(async () => {
  await refreshData();
});
</script>

<style lang="scss" scoped>
.Summary {
  background: #fff;
  padding: 30px;
  height: 700px;
  margin-bottom: 20px;
  .feature {
    display: flex;
    align-items: center;
    .AutoNum {
      margin-right: 30px;
      .el-input-number {
        margin: 0 5px;
      }
      .countdown {
        color: red;
      }
    }
  }
}
.grid-content {
  border: 1px solid red;
  text-align: center;

  .el-statistic__head {
    font-size: 50px;
  }
  .el-statistic__content {
    font-size: 50px;
  }
}
.line {
  height: 450px;
}
</style>